import {
	checkLogin
} from '@/util/utils.js'
import * as storage from '@/util/storage.js'
const delayTime = 120 * 1000

function doNewWebSocket() {
	if (ws) {
		return
	}
	checkLogin({})
	console.log("doNewWebSocket()")
	const accessToken = storage.getToken()
	const language = storage.getLanguage()
	const wsUrl = storage.getWebSocketUrl()
	try {
		uni.connectSocket({
			url: `${wsUrl}?accessToken=${accessToken}&language=${language}`
		});
		uni.onSocketOpen(e => {
			console.log('ws connect success')
			isConnect = true
			eList.forEach(item => {
				if (item) {
					if (isFunction(item.onopen)) {
						item.onopen(e)
					}
					if (item.room) {
						bindRoom(item.room)
					}
				}
			})
		})
		uni.onSocketError(e => {
			console.error(e)
			eList.forEach(item => {
				if (item && isFunction(item.onerror)) {
					item.onerror(e)
				}
			})
			ws.close()
			ws = null
			isConnect = false
		})
		uni.onSocketClose(e => {
			console.error(e)
			eList.forEach(item => {
				if (item && isFunction(item.onclose)) {
					item.onclose(e)
				}
			})
			ws = null
			isConnect = false
			setTimeout(() => {
				doNewWebSocket()
			}, delayTime)
		})
		uni.onSocketMessage(e => {
			const data = JSON.parse(e.data)
			eList.forEach(item => {
				if (item && item.room === data.room && isFunction(item.onmessage)) {
					item.onmessage(data)
				}
			})
		})
		ws = {}
	} catch (e) {
		setTimeout(() => {
			doNewWebSocket()
		}, delayTime)
	}

}

function isFunction(fn) {
	if (!fn) {
		return false
	}
	return Object.prototype.toString.call(fn) === '[object Function]'
}

let ws
let isConnect = false
const eList = []

export function listenWebSocket(param) {
	if (!ws) {
		doNewWebSocket()
	}
	let haveRoom = false
	eList.forEach(item => {
		if (item && item.room === param.room) {
			haveRoom = true
		}
	})
	eList.push(param)
	if (!haveRoom) {
		bindRoom(param.room)
	}

}

export function leaveWebSocket(param) {
	for (const i in eList) {
		const item = eList[i]
		if (item === param) {
			console.log('leave ' + param.room)
			eList.splice(i, 1)
		}
	}
	let haveRoom = false
	eList.forEach(item => {
		if (item && item.room === param.room) {
			haveRoom = true
		}
	})
	if (!haveRoom) {
		unBindRoom(param.room)
	}
}


function bindRoom(room) {
	if (!ws || !isConnect) {
		console.error(`bindRoom ${room} worry`)
		return
	}
	uni.sendSocketMessage({
		data: JSON.stringify({
			cmd: 'bindRoom',
			param: room
		})
	});
	console.log('ws bindRoom ' + room)
}

function unBindRoom(room) {
	if (!ws || !isConnect) {
		console.error(`unBindRoom ${room} worry`)
		return
	}
	uni.sendSocketMessage({
		data: JSON.stringify({
			cmd: 'unBindRoom',
			param: room
		})
	});
	console.log('ws unBindRoom ' + room)
}
